<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="告警名称" prop="alarmName">
        <el-input
          v-model="queryParams.alarmName"
          placeholder="请输入告警名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="告警级别" prop="alarmLevel">
        <el-select v-model="queryParams.alarmLevel" placeholder="请选择告警级别" clearable>
          <el-option
            v-for="dict in dict.type.iot_alarm_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:alarm:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:alarm:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="alarmConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="告警名称" align="center" prop="alarmName" />
      <el-table-column label="告警级别" align="center" prop="alarmLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_alarm_level" :value="scope.row.alarmLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status === 1 ? '0' : '1'"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:alarm:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:alarm:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改告警配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body custom-class="alarm-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="alarm-form">
        <div class="form-section">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="告警名称" prop="alarmName" required>
                <el-input v-model="form.alarmName" placeholder="请输入告警名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="告警级别" prop="alarmLevel" required>
                <el-select v-model="form.alarmLevel" placeholder="提醒通知" style="width: 100%">
                  <el-option
                    v-for="dict in dict.type.iot_alarm_level"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="告警状态" prop="status" class="status-item">
                <el-switch
                  v-model="form.status"
                  active-text="启用"
                  inactive-text="停用"
                  :active-value="1"
                  :inactive-value="0"
                  class="status-switch"
                ></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注信息" prop="remark">
                <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="tabs-section">
          <div class="tabs-header">
            <el-tabs v-model="activeTab">
              <el-tab-pane label="关联场景" name="scene">
                <div class="scene-content">
                  <el-table :data="sceneList" style="width: 100%" class="scene-table">
                    <el-table-column prop="sceneName" label="场景名称" min-width="120"/>
                    <el-table-column prop="isEnabled" label="状态" width="100">
                      <template slot-scope="scope">
                        <el-tag :type="scope.row.isEnabled ? 'success' : 'info'">
                          {{ scope.row.isEnabled ? '启用' : '停用' }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="matchMode" label="触发条件" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.matchMode === 1 ? '任意条件' : scope.row.matchMode === 2 ? '所有条件' : '不满足' }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="execType" label="执行方式" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.execType === 1 ? '顺序执行' : '同时执行' }}
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80" align="center">
                      <template slot-scope="scope">
                        <el-button
                          size="mini"
                          type="text"
                          icon="el-icon-delete"
                          @click="handleSceneDelete(scope.row)"
                        >删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-tab-pane>
              <el-tab-pane label="消息通知" name="notification">
                <div class="notification-content">
                  <!-- notification content -->
                </div>
              </el-tab-pane>
            </el-tabs>
            <div class="operation-btns" v-if="activeTab === 'scene'">
              <el-button type="text" icon="el-icon-refresh" @click="refreshScenes">刷新</el-button>
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddScene">添加场景</el-button>
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ form.id ? '修改' : '新增' }}</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <!-- 添加场景选择组件 -->
    <scene-select ref="sceneSelect" @selectScenes="handleSceneSelect" />
  </div>
</template>

<script>
import { listAlarmconfig, getAlarmconfig, delAlarmconfig, addAlarmconfig, updateAlarmconfig } from "@/api/iot/alarmconfig";
import { listScene } from "@/api/iot/scene";
import SceneSelect from "./sceneSelect";

export default {
  name: "AlarmConfig",
  dicts: ['sys_normal_disable', 'iot_alarm_level'],
  components: {
    SceneSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 告警配置表格数据
      alarmConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        alarmName: null,
        alarmLevel: null,
        status: null
      },
      // 表单参数
      form: {
        id: null,
        alarmName: null,
        alarmLevel: null,
        status: 0,
        remark: null
      },
      // 表单校验
      rules: {
        alarmName: [
          { required: true, message: "告警名称不能为空", trigger: "blur" }
        ],
        alarmLevel: [
          { required: true, message: "告警级别不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      // 场景列表数据
      sceneList: [],
      // 当前激活的标签页
      activeTab: 'scene'
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询告警配置列表 */
    getList() {
      this.loading = true;
      listAlarmconfig(this.queryParams).then(response => {
        this.alarmConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        alarmName: null,
        alarmLevel: null,
        status: 0,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加告警配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAlarmconfig(id).then(response => {
        this.form = response.data;
        // 如果有关联场景，加载场景信息
        if (this.form.sceneIds && this.form.sceneIds.length > 0) {
          // 调用场景列表接口获取场景详细信息
          listScene({
            ids: this.form.sceneIds
          }).then(res => {
            this.sceneList = res.rows.map(scene => ({
              id: scene.id,
              sceneName: scene.sceneName,
              isEnabled: scene.isEnabled,
              matchMode: scene.matchMode,
              execType: scene.execType,
              createTime: scene.createTime
            }));
          });
        }
        this.open = true;
        this.title = "修改告警配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 构建场景关联数据
          const sceneIds = this.sceneList.map(scene => scene.id);
          const submitData = {
            ...this.form,
            sceneIds: sceneIds
          };
          
          if (this.form.id != null) {
            updateAlarmconfig(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAlarmconfig(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除告警配置编号为"' + ids + '"的数据项？').then(function() {
        return delAlarmconfig(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/alarmconfig/export', {
        ...this.queryParams
      }, `alarmconfig_${new Date().getTime()}.xlsx`)
    },
    /** 刷新场景列表 */
    refreshScenes() {
      if (this.form.id) {
        getAlarmconfig(this.form.id).then(response => {
          const sceneIds = response.data.sceneIds;
          if (sceneIds && sceneIds.length > 0) {
            listScene({
              ids: sceneIds
            }).then(res => {
              this.sceneList = res.rows.map(scene => ({
                id: scene.id,
                sceneName: scene.sceneName,
                isEnabled: scene.isEnabled,
                matchMode: scene.matchMode,
                execType: scene.execType,
                createTime: scene.createTime
              }));
            });
          } else {
            this.sceneList = [];
          }
        });
      } else {
        // 如果是新增状态，直接清空场景列表
        this.sceneList = [];
      }
    },
    /** 添加场景按钮操作 */
    handleAddScene() {
      this.$refs.sceneSelect.show();
    },
    /** 处理场景选择结果 */
    handleSceneSelect(scenes) {
      // 将选中的场景添加到场景列表中
      scenes.forEach(scene => {
        // 检查是否已存在
        const exists = this.sceneList.some(item => item.id === scene.id);
        if (!exists) {
          // 确保所有必要的字段都被传递
          this.sceneList.push({
            id: scene.id,
            sceneName: scene.sceneName,
            isEnabled: scene.isEnabled,
            matchMode: scene.matchMode,
            execType: scene.execType,
            createTime: scene.createTime
          });
        }
      });
    },
    /** 编辑场景 */
    handleSceneEdit(row) {
      // TODO: 实现编辑场景逻辑
    },
    /** 删除场景 */
    handleSceneDelete(row) {
      const index = this.sceneList.findIndex(item => item.id === row.id);
      if (index !== -1) {
        this.sceneList.splice(index, 1);
      }
    }
  }
};
</script>

<style scoped>
.alarm-dialog {
  .el-dialog__body {
    padding: 20px 30px;
  }
}

.alarm-form {
  .el-form-item {
    margin-bottom: 22px;
  }
  
  .el-form-item__label {
    font-size: 14px;
    color: #606266;
  }
  
  .el-form-item__label::before {
    content: '';
    margin-right: 0;
  }
  
  .el-form-item.is-required .el-form-item__label::before {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
  }
}

.form-section {
  margin-bottom: 20px;
}

.status-item {
  margin-bottom: 0;
}

.tabs-section {
  border-top: 1px solid #E4E7ED;
  padding-top: 20px;
}

.tabs-header {
  position: relative;
  margin-bottom: 15px;
}

::v-deep .el-tabs__header {
  margin-bottom: 15px;
}

::v-deep .el-tabs__nav-wrap {
  margin-right: 150px;  /* 为按钮预留空间 */
}

::v-deep .el-tabs__nav-wrap::after {
  display: none;  /* 隐藏tab下方的横线 */
}

::v-deep .el-tabs__item {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  padding: 0 20px;
}

.operation-btns {
  position: absolute;
  right: 0;
  top: 0;
  height: 40px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding-right: 15px;
}

.scene-content {
  margin-top: 20px;
}
</style> 